#!/usr/bin/env python
# coding=utf-8
"""
@file: color_util.py
@contact: bianzhiwei@iyoujia.com
@time   : 2019/4/28 10:26 
@Desc   :
"""
import os
import random
import pandas as pd
from report_system.utils.log_util import log

pwd, filename = os.path.split(os.path.abspath(__file__))
# 当前文件的父路径
father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + ".")

colors_b = ['#FFFFFF', '#FFFFF0', '#FFFFE0', '#FFFF00', '#FFFAFA', '#FFFAF0', '#FFFACD', '#FFF8DC', '#FFF68F',
            '#FFF5EE', '#FFF0F5', '#FFEFDB', '#FFEFD5', '#FFEC8B', '#FFEBCD', '#FFE7BA', '#FFE4E1', '#FFE4C4',
            '#FFE4B5', '#FFE1FF', '#FFDEAD', '#FFDAB9', '#FFD700', '#FFD39B', '#FFC1C1', '#FFC125', '#FFC0CB',
            '#FFBBFF', '#FDF5E6', '#FCFCFC', '#FAFAFA', '#FAFAD2', '#FAF0E6', '#FAEBD7', '#FA8072', '#F8F8FF',
            '#F7F7F7', '#F5FFFA', '#F5F5F5', '#F5F5DC', '#F5DEB3', '#F4F4F4', '#F4A460', '#F2F2F2', '#F0FFFF',
            '#F0FFF0', '#F0F8FF', '#F0F0F0', '#F0E68C', '#F08080', '#EEEEE0', '#EEEED1', '#EEEE00', '#EEE9E9',
            '#EEE9BF', '#EEE8CD', '#EEE8AA', '#EEE685', '#EEE5DE', '#EEE0E5', '#EEDFCC', '#EEDC82', '#EED8AE',
            '#EED5D2', '#EAEAEA', '#E9967A', '#E8E8E8', '#E6E6FA', '#E5E5E5', '#E3E3E3', '#E0FFFF', '#E0EEEE',
            '#E0EEE0', '#E0E0E0', '#E066FF', '#DEDEDE', '#DEB887', '#DDA0DD', '#DCDCDC', '#DC143C', '#DBDBDB',
            '#DB7093', '#DAA520', '#DA70D6', '#D9D9D9', '#D8BFD8', '#D6D6D6', '#D4D4D4', '#D3D3D3', '#D2B48C',
            '#D2691E', '#D1EEEE', '#D1D1D1', '#D15FEE', '#D02090', '#CFCFCF', '#CDCDC1', '#CDCDB4', '#CDCD00',
            '#CDC9C9', '#CDC9A5', '#CDC8B1', '#CDC673', '#CDC5BF', '#CAFF70', '#CAE1FF', '#C9C9C9', '#C7C7C7',
            '#C4C4C4', '#C2C2C2', '#C1FFC1', '#C1CDCD', '#C1CDC1', '#C1C1C1', '#C0FF3E', '#BFEFFF', '#00FFFF',
            '#00FF7F', '#00FF00', '#00FA9A', '#00F5FF', '#00EEEE', '#00EE76', '#00EE00', '#00E5EE', '#00CED1',
            '#00CDCD', '#00CD66', '#00CD00', '#00C5CD', '#00BFFF', '#00B2EE', '#009ACD', '#008B8B']


def get_colors(num):
    """
    :param num: 想要获取多少种颜色
    :return:
    """
    # 随机返回 有 num 个值的list
    return random.sample(colors_b, num)


def get_color_dict(columns: list):
    if isinstance(columns, str):
        columns = [columns]
    colors = get_colors(columns.__len__())

    return dict((name, value) for name, value in zip(columns, colors))


def style_select(df, color='#FFF0F5', uuid=None):
    if isinstance(df, pd.DataFrame):
        df = df.style
    if uuid:
        df.uuid = uuid
    df_2 = df.set_table_styles([{'selector': 'tr:hover', 'props': [('background-color', color)]}])
    return df_2


def style_color(df, colors, uuid=None, **kwargs):
    log.info('----------> 正在处理颜色！<------------')
    # log.info(colors)
    df = df.astype(float, errors='ignore')
    if isinstance(df, pd.DataFrame):
        df = df.style
    if uuid:
        df.uuid = uuid
    style_df = df.apply(style_apply, colors=colors, kwargs=kwargs)
    log.info('----------> 处理颜色完毕！<------------')
    return style_df


def style_apply(series, colors, **kwargs):
    """
    [('border-bottom-color', 'blue'),
     ('border-left-color', 'red'),
     ('border-right-color', 'red'),
     ('border-top-color', 'blue'),
     ('font-family', 'serif'),
     ('font-size', '24pt'),
     ('font-weight', 'bold')]
     ('max-width')
     border-color: BLUE RED;
    ...               font-size: 1em;
    ...               font-size: 2em;
    ...               font-weight: normal;
    ...               font-weight: inherit;

    'font-family': 'serif', 'font-weight': 'bold'
    :param series: 传过来的数据是DataFrame中的一列   类型为pd.Series
    :param colors: 内容是字典  其中key 为标题名   value 为颜色
    :return:
    """
    # print(series,type(series))
    series_names = series.name
    first_name = series_names[0]
    # log.info('正在处理一级标题：{} 的颜色'.format(first_name))
    # second_name = series_names[1] if len(series_names) > 1 else ''
    back_ground = ''
    if isinstance(colors, str):
        back_ground = 'background-color: ' + colors
    elif isinstance(colors, dict):
        if first_name in colors:
            back_ground = 'background-color: ' + colors[first_name]
    else:
        log.info('有问题')
    # back_ground_list = list()
    # for cell in series:
    #
    #     back_ground_list.append(back_ground)
    back_ground_list = [back_ground for cell in series]

    return back_ground_list


def highlight_max(x):
    """
    获取每一列的最大值
    :param x:
    :return:
    """
    return ['background-color: yellow' if v == x.max() else '' for v in x]


def style_df_to_html(df_dict, html_name, file_name=None, color='#FFF0F5', uuid=None):
    """
    pd.Style  也就是带颜色的DataFrame 转化成html
    由于这个html吧中文乱码  所以给他加一行编码
    又由于吧  这个 表格不是黑色的  是白色的  所以把  给替换一下边框
    :param df_dict:
    :param html_name:
    :param file_name:
    :param uuid:
    :param color:
    :return:
    """
    # 由于这个html吧中文乱码  所以给他加一行编码
    start_html = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'
    # if isinstance(df,pd.DataFrame):
    #     pd.DataFrame.to_html()
    file_name = file_name if file_name else html_name
    html_path = father_path + '/report_html/' + file_name + '.html'
    if html_name in df_dict:
        df = df_dict[html_name]
        df = style_select(df, color=color, uuid=uuid)
        # <pandas.io.formats.style.Styler object at 0x11a0695c0>
        # pd.DataFrame.style.__sizeof__()
        # print(df.__sizeof__())
        # df = df.applymap(str, errors='ignore')
        html = start_html + df.render()
        # 又由于吧  这个 表格不是黑色的  是白色的  所以把  给替换一下边框
        html = html.replace('<table id', '<table border="2px"bordercolor="#A2B5CD"cellspacing="0"text-align="center"id')
        html = html.replace('<style  type="text/css" >', '<style  type="text/css"  text-align="center" " >')
        log.info('正在处理生成写入html: ' + html_path)
        with open(html_path, 'w') as f:
            f.writelines(html)

        # path = father_path + '/report_files/'
    else:
        html = None
    return html


def compare_variable(df, val1, val2, color="yellow"):
    if isinstance(df, pd.DataFrame):
        df = df.style
    style_df = df.apply(compare_variable_apply, val1=val1, val2=val2, color=color, axis=1)
    return style_df


def compare_variable_apply(row, val1, val2, color="yellow"):
    dict_row = dict(row)
    if row[val1] != row[val2] and row[val1] is not None and row[val1] != "" \
            and row[val2] is not None and row[val2] != "":
        col = 'background-color: ' + color
    else:
        col = ""
    return [col if key == val1 or key == val2 else "" for key in dict_row]


def aaa(x):
    print(x)


if __name__ == '__main__':
    temp_df = pd.DataFrame([['1', None, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]])
    temp_df.columns = ['A', 'B', 'C', 'D', 'E']
    # temp_df.apply(aaa, axis=1)
    compare_variable(temp_df, 'A', 'E')
